// WMS Library - http://wmslib.codeplex.com/
// Copyright (c) Tom Gaskins 2004 - Erik Putrycz 2013
// Licensed under the Microsoft Public License (Ms-PL)

using System;
using System.Net;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
using WMSLib.WMSTools;
using System.Diagnostics;

namespace WMSLib.Client
{
    /// <summary>
    /// Represents a WMS server and holds its capabilities description.
    /// </summary>
    public class Server
    {
        private WMSLib.Client.Capabilities _capabilities;
        private Uri _uri;
        private string _svrUrl;
        private string _legendURL;

        public Server(string srvUrl, string logoURL = null)
        {
            _svrUrl = srvUrl;
            _legendURL = logoURL;
            var capabilitiesURL = @"VERSION=1.1.1&lang=E&service=WMS&request=GetCapabilities";
            _uri = new Uri(srvUrl + capabilitiesURL);
            Debug.WriteLine("Using {0} for capabilities", _uri);
            _capabilities = new Capabilities(this);
        }

        public async Task<bool> LoadData()
        {
            using (var client = new HttpClient())
            {
                using (var ws = await client.GetStreamAsync(_uri))
                {
                    _capabilities.LoadData(ws);
                }
            }
            return true;
        }

        public Capabilities Capabilities
        {
            get { return this._capabilities; }
        }

        public string ServerRootURL
        {
            get { return _svrUrl; }
        }

        //public System.Uri Uri
        //{
        //    get {return new System.Uri(this.capabilities.GetCapabilitiesRequestUri);}
        //}

        //public MapRequestBuilder CreateMapRequest()
        //{
        //    return new MapRequestBuilder(new System.Uri(this.capabilities.GetMapRequestUri));
        //}

        public string AttributionURI { get { return _legendURL; } }
    }
}